package nl.janvanloenen.bkc;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.LayoutParams;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CompetitionFragment extends Fragment implements
		OnChildClickListener {

	SavedTabsListAdapter adapter;
	ExpandableListView elv;
	DatabaseHandler db;
	List<Match> AllMatches;
	List<Match> today;
	List<Match> future;
	List<Match> past;

	private boolean run;
	private Handler h;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_competition, null);
		adapter = new SavedTabsListAdapter();
		elv = (ExpandableListView) v.findViewById(R.id.expandableListView1);
		elv.setAdapter(adapter);
		elv.setOnChildClickListener(this);

		setLists();

		// in create time
		h = new Handler();
		// call where you want
		h.postDelayed(myRunnable2, 10000); // after 10000 millisecond this
											// function call automatically
		run = true;

		return v;
	}

	@Override
	public void onResume() {
		super.onResume();
		db = new DatabaseHandler(getActivity());
		run = true;
	}

	@Override
	public void onPause() {
		super.onPause();
		db.close();
		run = !true;
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		setLists();
		adapter.setChildren();
	}

	public void setLists() {
		// make new database handler..
		db = new DatabaseHandler(getActivity());
		// Reading DB
		AllMatches = db.getAllMatches();
		System.out.println("er zijn: " + AllMatches.size()
				+ " webstrijden in de DB");

		List<Match> xPast = new ArrayList<Match>();
		List<Match> xToday = new ArrayList<Match>();
		List<Match> xFuture = new ArrayList<Match>();

		final Calendar c = Calendar.getInstance();

		Date today = new Date(c.get(Calendar.YEAR) - 1900,
				c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
		// Date today = new Date(2013-1900, 8-1, 6);
		System.out.println(today.toString());
		for (Match i : AllMatches) {
			Date date = null;
			try {
				date = Date.valueOf(i.getDate());
			} catch (Exception e) {
				date = today;
				e.printStackTrace();
			}

			if (date.equals(today)) {
				// vandaag
				xToday.add(i);
				CompetitionFragment.this.today = xToday;
			} else if (date.before(today)) {
				// voor vandaag
				xFuture.add(i);
				CompetitionFragment.this.future = xFuture;
			} else if (date.after(today)) {
				// na vandaag
				xPast.add(i);
				CompetitionFragment.this.past = xPast;
			} else {
				System.out.println("something went wrong...");
			}
		}
	}

	public class SavedTabsListAdapter extends BaseExpandableListAdapter {

		private String[] groups = { "Vandaag", "Recente Uitslagen",
				"Komende wedstrijden" };

		private String[][] children = { getToday(), getPast(), getFuture() };

		private String[] getToday() {
			List<String> where = new ArrayList<String>();
			String[] string = null;

			try {
				for (Match cn : today) {
					where.add(cn.getTeamA() + " - " + cn.getTeamB());
				}

				if (where.size() != 0) {
					string = new String[where.size()];
					where.toArray(string);
				}
			} catch (Exception e) {
				// e.printStackTrace();
			}

			return string;
		}

		private String[] getPast() {
			List<String> where = new ArrayList<String>();
			String[] string = null;

			try {
				for (Match cn : past) {
					where.add(cn.getTeamA() + " - " + cn.getTeamB());
				}

				if (where.size() != 0) {
					string = new String[where.size()];
					where.toArray(string);
				}
			} catch (Exception e) {
				// e.printStackTrace();
			}

			return string;
		}

		private String[] getFuture() {
			List<String> where = new ArrayList<String>();
			String[] string = null;

			try {
				for (Match cn : future) {
					where.add(cn.getTeamA() + " - " + cn.getTeamB());
				}

				if (where.size() != 0) {
					string = new String[where.size()];
					where.toArray(string);
				}
			} catch (Exception e) {
				// e.printStackTrace();
			}
			return string;
		}

		public void setChildren() {
			String[][] children2 = { getToday(), getPast(), getFuture() };

			children = children2;
		}

		@Override
		public int getGroupCount() {
			return groups.length;
		}

		@Override
		public int getChildrenCount(int i) {
			int count = 0;
			try {
				count = children[i].length;
			} catch (Exception e) {

			}
			return count;
		}

		@Override
		public Object getGroup(int i) {
			return groups[i];
		}

		@Override
		public Object getChild(int i, int i1) {
			setChildren();
			return children[i][i1];
		}

		@Override
		public long getGroupId(int i) {
			return i;
		}

		@Override
		public long getChildId(int i, int i1) {
			return i1;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		public String getDateForMatch(int i, int i1) {
			System.out.println(" ID = " + i + " , " + i1);
			try {
				if (i == 0) {
					Match cn = today.get(i1);
					return cn.getDate().toString();
				} else if (i == 1) {
					Match cn = future.get(i1);
					return cn.getDate().toString();
				} else if (i == 2) {
					Match cn = past.get(i1);
					return cn.getDate().toString();
				}
			} catch (Exception e) {
				return "";
			}
			return "";
		}

		public String getScoreForMatch(int i, int i1) {
			try {
				if (i == 0) {
					Match cn = today.get(i1);
					return cn.getScoreTeamA() + " - " + cn.getScoreTeamB();
				} else if (i == 1) {
					Match cn = future.get(i1);
					return cn.getScoreTeamA() + " - " + cn.getScoreTeamB();
				} else if (i == 2) {
					Match cn = past.get(i1);
					return cn.getScoreTeamA() + " - " + cn.getScoreTeamB();
				}
			} catch (Exception e) {
				return "";
			}
			return "";
		}

		@Override
		public View getGroupView(int i, boolean b, View view,
				ViewGroup viewGroup) {
			TextView textView = new TextView(
					CompetitionFragment.this.getActivity());
			textView.setText(getGroup(i).toString());
			textView.setTextSize(20);
			textView.setPadding(75, 10, 5, 10);
			return textView;
		}

		@Override
		public View getChildView(int i, int i1, boolean b, View view,
				ViewGroup viewGroup) {
			View v = new View(getActivity());

			LinearLayout layout = new LinearLayout(getActivity());
			layout.setOrientation(0);
			LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
			layout.setLayoutParams(parms);
			layout.setBackgroundColor(Color.LTGRAY);

			LinearLayout layout1 = new LinearLayout(getActivity());
			layout1.setOrientation(1);
			LinearLayout.LayoutParams parms1 = new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1);
			layout1.setLayoutParams(parms1);
			layout1.setGravity(Gravity.LEFT);

			LinearLayout layout2 = new LinearLayout(getActivity());
			layout2.setOrientation(1);
			LinearLayout.LayoutParams parms2 = new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1);
			layout2.setLayoutParams(parms2);
			layout2.setGravity(Gravity.RIGHT);

			// textview : team A - team B
			TextView textView = new TextView(
					CompetitionFragment.this.getActivity());
			textView.setText(getChild(i, i1).toString());
			textView.setTextSize(15);
			textView.setPadding(15, 10, 5, 10);

			// textview 2 : date
			TextView textView2 = new TextView(
					CompetitionFragment.this.getActivity());
			textView2.setText(getDateForMatch(i, i1));
			textView2.setTextSize(10);
			textView2.setPadding(25, 0, 5, 5);

			// textview 3 : date
			TextView textView3 = new TextView(
					CompetitionFragment.this.getActivity());
			textView3.setText(getScoreForMatch(i, i1));
			textView3.setGravity(Gravity.RIGHT);
			textView3.setTextSize(20);
			textView3.setPadding(0, 20, 30, 0);

			// add to layout
			layout.addView(layout1);
			layout.addView(layout2);
			layout1.addView(textView);
			layout1.addView(textView2);
			layout2.addView(textView3);

			return layout;
		}

		@Override
		public boolean isChildSelectable(int i, int i1) {
			return true;
		}
	}

	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		Intent openGame = new Intent("nl.janvanloenen.bkc.Game");
		openGame.putExtra("ID", getIdForMatch(groupPosition, childPosition));
		startActivity(openGame);
		return true;
	}

	public int getIdForMatch(int i, int i1) {
		if (i == 0) {
			Match cn = today.get(i1);
			return cn.getID();
		} else if (i == 1) {
			Match cn = future.get(i1);
			return cn.getID();
		} else if (i == 2) {
			Match cn = past.get(i1);
			return cn.getID();
		}
		return 0;
	}

	// this function
	private Runnable myRunnable2 = new Runnable() {
		public void run() {
			// do some thing
			while (run) {
				try {
					synchronized (myRunnable2) {
						wait(10000);
						setLists();

						adapter.setChildren();
						adapter.notifyDataSetChanged();
						adapter.notifyAll();
					}
				} catch (Exception e) {
					System.out.println("myRunable2 Exception");
					e.printStackTrace();

				}

			}

		}
	};
}
